// FacebookFbmlSession.cs
// Facebook/FrameworkWeb/Web
// Copyright (c) 2007, Nikhil Kothari. All Rights Reserved.
//

using System;
using System.Diagnostics;
using System.Web;
using Facebook.Service.Core;

namespace Facebook.Web {

    internal sealed class FacebookFbmlSession : FacebookServerSession {

        public FacebookFbmlSession(FacebookApplication application, string appKey, string secret)
            : base(application, appKey, secret) {
        }

        protected internal override string Initialize(HttpContext context) {
            base.Initialize(context);

            string redirectUrl = null;
            HttpRequest request = context.Request;

            FacebookSessionType sessionType = FacebookSessionType.User;

            string sessionKey = request["fb_sig_session_key"];
            bool sessionExpires = (String.CompareOrdinal(request["fb_sig_expires"], "0") != 0);
            string userID = request["fb_sig_user"];
            string pageUserID = null;

            if (String.IsNullOrEmpty(request["fb_page_id"]) == false) {
                pageUserID = userID;
                userID = request["fb_page_id"];
            }

            if (String.IsNullOrEmpty(sessionKey) || String.IsNullOrEmpty(userID)) {
                string authToken = request["auth_token"];

                if (String.IsNullOrEmpty(authToken) == false) {
                    FacebookRequest sessionRequest = new FacebookRequest(this);
                    string dummy;

                    sessionKey = sessionRequest.CreateSession(authToken, out userID, out sessionExpires, out dummy);
                    Debug.Assert(String.IsNullOrEmpty(dummy));
                }
            }

            if (!String.IsNullOrEmpty(sessionKey) && !String.IsNullOrEmpty(userID)) {
                if (String.IsNullOrEmpty(pageUserID) == false) {
                    sessionType = FacebookSessionType.PresencePage;
                }

                InitializeSessionKey(sessionKey, sessionExpires, sessionType);
                InitializeUserID(userID, pageUserID);
            }
            else {
                redirectUrl = String.Format(FacebookLoginUrl, ApplicationKey);
            }

            if ((redirectUrl == null) && (Application.IsApplicationAdded == false)) {
                redirectUrl = String.Format(FacebookAddAppUrl, ApplicationKey);
            }
            return redirectUrl;
        }
    }
}
